import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, message, Popconfirm, Select, Input, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, PartitionOutlined, ApiOutlined, MenuOutlined, ToolOutlined } from '@ant-design/icons';
import { request } from 'umi';
import PermissionForm from './PermissionForm';
import SearchForm from './SearchForm';
import moment from 'moment';
import AuthorizedButton from '@/components/Authorized/AuthorizedButton';

// 获取权限列表
const fetchPermissions = async (params) => {
  return request('/api/v1/permission', {
    method: 'GET',
    params,
  });
};

// 创建权限
const createPermission = async (data) => {
  return request('/api/v1/permission', {
    method: 'POST',
    data,
  });
};

// 更新权限
const updatePermission = async (data) => {
  return request(`/api/v1/permission/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除权限
const deletePermission = async (id) => {
  return request(`/api/v1/permission/${id}`, {
    method: 'DELETE',
  });
};

// 将权限列表转换为树形结构
const convertToTreeData = (permissions) => {
  // 找出所有顶级权限（parent_id为0或null的）
  const rootPermissions = permissions.filter(p => !p.parent_id);
  
  // 递归构建树
  const buildTree = (parentPermissions) => {
    return parentPermissions.map(parent => {
      // 找出所有以当前权限为父级的子权限
      const children = permissions.filter(p => p.parent_id === parent.id);
      
      return {
        ...parent,
        key: parent.id,
        children: children.length > 0 ? buildTree(children) : [],
      };
    });
  };
  
  return buildTree(rootPermissions);
};

const PermissionList = () => {
  const [permissions, setPermissions] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加权限');
  const [form] = Form.useForm();
  const [batchForm] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [currentPermission, setCurrentPermission] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  // 批量设置父级权限相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [batchParentModalVisible, setBatchParentModalVisible] = useState(false);

  // 搜索参数
  const [searchParams, setSearchParams] = useState({});
  
  // 是否使用树形结构显示
  const [useTreeView, setUseTreeView] = useState(true);

  // 获取权限列表
  const fetchPermissionList = async () => {
    try {
      setLoading(true);
      const res = await fetchPermissions({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        const permissionList = res.data || [];
        setPermissions(permissionList);
        // 将扁平数据转换为树形结构
        setTreeData(convertToTreeData(permissionList));
      } else {
        message.error(res.message || '获取权限列表失败');
      }
    } catch (error) {
      console.error('获取权限列表出错:', error);
      message.error('获取权限列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPermissionList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
    },
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text, record) => {
        // 根据权限类型显示不同的图标
        let icon;
        switch(record.type) {
          case 'api':
            icon = <ApiOutlined style={{ color: '#52c41a' }} />;
            break;
          case 'menu':
            icon = <MenuOutlined style={{ color: '#faad14' }} />;
            break;
          case 'button':
            icon = <ToolOutlined style={{ color: '#f5222d' }} />;
            break;
          default:
            icon = <ApiOutlined style={{ color: '#52c41a' }} />;
        }
        
        return (
          <span>
            {icon} {text}
          </span>
        );
      },
    },
    {
      title: '权限标识符',
      dataIndex: 'identifier', // 后端返回的是code，对应前端的identifier
      key: 'identifier',
      width: 180,
    },
    {
      title: '所属模块',
      dataIndex: 'module',
      key: 'module',
      width: 120,
    },
    {
      title: '权限类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (text) => {
        const typeMap = {
          api: 'API接口',
          menu: '菜单',
          button: '按钮',
        };
        return typeMap[text] || text;
      },
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      key: 'method',
      width: 100,
      render: (text, record) => {
        return record.type === 'api' ? (text || '-') : '-';
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: '父级权限',
      dataIndex: 'parent_id',
      key: 'parent_id',
      width: 150,
      render: (parentId) => {
        const parentPermission = permissions.find((permission) => permission.id === parentId);
        return parentPermission ? parentPermission.name : '-';
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => (
        <span style={{ color: status === 1 ? '#52c41a' : '#ff4d4f' }}>
          {status === 1 ? '正常' : '禁用'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <AuthorizedButton 
            permission="permission:create"
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </AuthorizedButton>
          <Popconfirm
            title="确定要删除此权限吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AuthorizedButton 
              permission="permission:delete"
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </AuthorizedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理添加权限
  const handleAdd = () => {
    setModalTitle('添加权限');
    setEditingId(null);
    setCurrentPermission(null);
    setModalVisible(true);
  };

  // 处理编辑权限
  const handleEdit = (record) => {
    setModalTitle('编辑权限');
    setEditingId(record.id);
    // 转换数据格式以匹配PermissionForm组件的字段
    const initialValues = {
      name: record.name,
      description: record.description,
      module: record.module,
      type: record.type,
      identifier: record.identifier, // 将code映射为identifier
      method: record.method,
      parent_id: record.parent_id,
      sort: record.sort,
      status: record.status === 1,
    };
    setCurrentPermission(initialValues);
    setModalVisible(true);
  };

  // 处理删除权限
  const handleDelete = async (id) => {
    try {
      const res = await deletePermission(id);
      if (res.success) {
        message.success('删除成功');
        fetchPermissionList();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除权限出错:', error);
      message.error('删除失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      
      // 转换数据格式以匹配后端API
      const submitData = {
        name: values.name,
        description: values.description,
        module: values.module,
        type: values.type,
        identifier: values.identifier, // 将identifier映射为code
        method: values.method,
        parent_id: parseInt(values.parent_id),
        sort: parseInt(values.sort),
        status: values.status ? 1 : 0,
      };
      
      let res;
      if (editingId) {
        // 更新权限
        res = await updatePermission({
          id: editingId,
          ...submitData,
        });
        if (res.success) {
          message.success('更新成功');
          setModalVisible(false);
          fetchPermissionList();
        } else {
          message.error(res.message || '更新失败');
        }
      } else {
        // 创建权限
        res = await createPermission(submitData);
        if (res.success) {
          message.success('创建成功');
          setModalVisible(false);
          fetchPermissionList();
        } else {
          message.error(res.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('提交表单出错:', error);
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination({
      ...pagination,
    });
  };

  // 处理搜索
  const handleSearch = (values) => {
    setSearchParams(values);
    setPagination({
      ...pagination,
      current: 1, // 搜索时重置为第一页
    });
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1, // 重置搜索时重置为第一页
    });
  };

  // 批量更新权限父级ID的API
  const batchUpdateParent = async (data) => {
    return request('/api/v1/permission/batch/parent', {
      method: 'POST',
      data,
    });
  };

  // 处理批量设置父级权限
  const handleBatchSetParent = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择需要设置的权限');
      return;
    }
    batchForm.resetFields();
    setBatchParentModalVisible(true);
  };

  // 提交批量设置父级权限
  const handleBatchParentSubmit = async () => {
    try {
      const values = await batchForm.validateFields();
      setLoading(true);
      
      const res = await batchUpdateParent({
        permissionIds: selectedRowKeys.map(id => parseInt(id)),
        parentId: parseInt(values.parentId) || 0,
      });
      
      if (res.success) {
        message.success('批量设置父级权限成功');
        setBatchParentModalVisible(false);
        setSelectedRowKeys([]);
        fetchPermissionList();
      } else {
        message.error(res.message || '批量设置父级权限失败');
      }
    } catch (error) {
      console.error('批量设置父级权限出错:', error);
      message.error('批量设置父级权限失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys) => {
      setSelectedRowKeys(selectedRowKeys);
    },
  };

  return (
    <PageContainer>
      <Card
        title="权限管理"
        extra={
          <Space>
            <AuthorizedButton 
              permission="permission:create" 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAdd}
            >
              添加权限
            </AuthorizedButton>
            <AuthorizedButton 
              permission="permission:update" 
              type="primary" 
              icon={<PartitionOutlined />}
              onClick={handleBatchSetParent}
              disabled={selectedRowKeys.length === 0}
            >
              批量设置父级
            </AuthorizedButton>
          </Space>
        }
      >
        <SearchForm onSearch={handleSearch} onReset={handleResetSearch} />
        <div style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            onClick={() => setUseTreeView(!useTreeView)}
            style={{ marginRight: 8 }}
          >
            {useTreeView ? '切换为列表视图' : '切换为树形视图'}
          </Button>
          <span style={{ marginLeft: 8 }}>
            当前模式: {useTreeView ? '树形视图' : '列表视图'}
          </span>
        </div>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={useTreeView ? treeData : permissions}
          rowKey="id"
          loading={loading}
          pagination={useTreeView ? false : pagination}
          onChange={handleTableChange}
          defaultExpandAllRows={useTreeView}
          indentSize={20}
          scroll={{ x: 1100 }}
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        footer={null}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <PermissionForm
          initialValues={currentPermission}
          onSubmit={handleSubmit}
          onCancel={() => setModalVisible(false)}
        />
      </Modal>

      {/* 批量设置父级权限弹窗 */}
      <Modal
        title="批量设置父级权限"
        visible={batchParentModalVisible}
        onOk={handleBatchParentSubmit}
        onCancel={() => setBatchParentModalVisible(false)}
        confirmLoading={loading}
      >
        <Form
          form={batchForm}
          layout="vertical"
        >
          <Form.Item
            name="parentId"
            label="父级权限"
            rules={[{ required: true, message: '请选择父级权限' }]}
          >
            <Select 
              showSearch 
              placeholder="请选择父级权限"
              filterOption={(input, option) => {
                const permission = permissions.find(p => p.id === option.value);
                if (option.value === 0) {
                  return '顶级权限'.toLowerCase().includes(input.toLowerCase());
                }
                if (!permission) return false;
                
                // 搜索权限名称、标识符和类型
                const typeMap = {
                  api: 'API接口',
                  menu: '菜单',
                  button: '按钮',
                };
                const typeName = typeMap[permission.type] || permission.type;
                
                return (
                  permission.name.toLowerCase().includes(input.toLowerCase()) ||
                  permission.identifier.toLowerCase().includes(input.toLowerCase()) ||
                  typeName.toLowerCase().includes(input.toLowerCase())
                );
              }}
              optionLabelProp="label"
            >
              <Select.Option value={0} label="顶级权限">顶级权限</Select.Option>
              {permissions.map(permission => {
                const typeMap = {
                  api: 'API接口',
                  menu: '菜单',
                  button: '按钮',
                };
                const typeName = typeMap[permission.type] || permission.type;
                const label = `${permission.name} [${permission.identifier}]`;
                
                return (
                  <Select.Option 
                    key={permission.id} 
                    value={permission.id}
                    label={label}
                  >
                    <div>
                      <div>{permission.name} <span style={{ color: '#1890ff' }}>[{permission.identifier}]</span></div>
                      <div><span style={{ 
                        color: permission.type === 'api' ? '#52c41a' : 
                               permission.type === 'menu' ? '#faad14' : '#f5222d',
                        fontSize: '12px'
                      }}>{typeName}</span></div>
                    </div>
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <div style={{ marginBottom: 8 }}>
            <p>已选择 {selectedRowKeys.length} 个权限</p>
            <p>说明：设置为0表示将权限设置为顶级权限</p>
          </div>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default PermissionList;